雖然基本的集合(如陣列或切片)僅能儲存相同資料類型的元素, 結構(structs) 我們可以將不同類型的資料整合為一個整體。這對於火星探測至關重要,因為遙測資料包含名稱(字串)和座標(float64)等混合資訊。
1. 語意分組與一致性
與僅能告訴你「有多少」的浮點數切片不同,結構提供了一個帶標籤的容器。 定義: 集合中的元素必須是同一類型,而結構則允許你將不同的資料聚合在一起。這種方式透過將相關資料打包成命名物件,避免了『變數亂湯』的問題。
a, b = b, a // 高效的狀態交換
2. 操作的原子性
透過將變數群組起來,我們達到了操作的原子性。例如函式 func Step(a, b Universe) 或 func (u Universe) Next(x, y int) bool 可以操作整個環境,而不必追尋零散的基本資料。對於一次性任務, 匿名結構 (如清單 21.1 所示)可在無需正式類型定義的情況下立即進行組織。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What primary advantage do structures have over individual variables?
They allow variables to occupy less memory.
They group related data into a cohesive unit.
They automatically encrypt data.
They allow for faster mathematical operations.
✅ Correct!
Correct! Structures provide semantic grouping, keeping related primitives together.❌ Incorrect
Structures are about organization and logic, not necessarily compression or speed.QUESTION 2
Which syntax correctly performs a state swap between two structs 'a' and 'b' in Go?
swap(a, b)
a, b = b, a
a.Update(b)
move b to a
✅ Correct!
Go supports multiple assignment, making swapping extremely concise.❌ Incorrect
Go's `a, b = b, a` is the idiomatic way to swap values without a temporary variable.QUESTION 3
How do structures differ from collections like slices or arrays?
Collections store disparate types; structs store uniform types.
Slices are immutable; structs are always mutable.
Collections store uniform types; structs store disparate types.
Structs cannot be passed to functions.
✅ Correct!
Exactly. A slice of floats only holds floats, but a struct can hold a string, a float, and a bool.❌ Incorrect
Remember the definition: Collections are of the same type; structures group disparate things.QUESTION 4
In Listing 21.1, how are the 'lat' and 'long' fields accessed?
Using bracket notation: curiosity['lat']
Using arrow notation: curiosity->lat
Using dot notation: curiosity.lat
Using the 'get' keyword: get(curiosity, lat)
✅ Correct!
Dot notation is the standard way to access struct fields in Go.❌ Incorrect
Go uses the dot (.) operator for member access.QUESTION 5
What is an 'anonymous structure'?
A struct that cannot be seen by other packages.
A struct defined without a formal type name for immediate use.
A struct that has no fields.
A struct used only for JSON encoding.
✅ Correct!
Yes. Listing 21.1 shows an anonymous struct variable used for curiosity's telemetry.❌ Incorrect
Anonymous structs are local, 'one-off' definitions without a 'type' keyword.Case Study: Martian Coordinate Systems
Applying Structural Logic to Habitat Data
As an engineer at Mission Control, you must manage habitat transitions and coordinate reporting. You are tasked with implementing functions that handle the 'Universe' of Martian data using Go structs and preparing data for transmission back to Earth.
Q
1. Write a Step function signature and explain how it performs an operation on two 'Universe' types. (Required: 30 words)
Solution:
The signature is `func Step(a, b Universe)`. It orchestrates state transitions by allowing the logic to manipulate two environmental states simultaneously, often utilizing the efficient swap `a, b = b, a`.
The signature is `func Step(a, b Universe)`. It orchestrates state transitions by allowing the logic to manipulate two environmental states simultaneously, often utilizing the efficient swap `a, b = b, a`.
Q
2. Take a look around. What entities in a Martian habitat could be represented with a structure instead of loose variables?
Solution:
Potential structures include: `Habitat` (O2 level, temperature, occupant count), `Rover` (battery life, speed, location), or `LifeSupport` (filter status, water reserves, power source).
Potential structures include: `Habitat` (O2 level, temperature, occupant count), `Rover` (battery life, speed, location), or `LifeSupport` (filter status, water reserves, power source).
Q
3. [Writing Task] Experiment: landing.go. Write a program snippet that would display JSON encoding for landing sites. (Include MarshalIndent requirement).
Solution:
Students should define a struct with tags: `type Site struct { Name string `json:"name"`; Lat float64 `json:"lat"` }`. Then use `data, _ := json.MarshalIndent(sites, "", " ")` and `fmt.Println(string(data))` to produce human-friendly telemetry.
Students should define a struct with tags: `type Site struct { Name string `json:"name"`; Lat float64 `json:"lat"` }`. Then use `data, _ := json.MarshalIndent(sites, "", " ")` and `fmt.Println(string(data))` to produce human-friendly telemetry.